package me.minecraft.plugin.itemsave.manager;

import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.File;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author langle__
 * @version 1.0
 */
public class ItemManager {

    public static final ItemManager INSTANCE = new ItemManager();

    private final Map<String, ItemStack> items = new ConcurrentHashMap<>();

    private ItemManager() {
    }

    @Nullable
    public ItemStack getItem(@NotNull String name) {
        ItemStack item = items.get(name);
        if (item != null) return item;
        return FileManager.INSTANCE.loadItem(name);
    }

    public boolean saveItem(@NotNull String name, @NotNull ItemStack item) {
        items.put(name, item);
        return FileManager.INSTANCE.saveItem(name, item);
    }

    public boolean deleteItem(@NotNull String name) {
        items.remove(name);
        return FileManager.INSTANCE.deleteItem(name);
    }

    public boolean exists(@NotNull String name) {
        return items.containsKey(name) || FileManager.INSTANCE.exists(name);
    }

    public Set<String> keySet() {
        return items.keySet();
    }

    public void load() {
        File[] files = FileManager.INSTANCE.getItemFolder().listFiles(f -> f.isFile() && f.getName().endsWith(".json"));
        if (files == null) return;
        for (File file : files) {
            ItemStack item = FileManager.INSTANCE.loadItem(file);
            if (item != null) {
                String fileName = file.getName();
                String name = fileName.substring(0, fileName.lastIndexOf('.'));
                items.put(name, item);
            }
        }
    }

}
